#!/bin/bash

SYSFS_GPIO=/sys/class/gpio
GPIONUM=(0 428 427 429 430 449 345 344)
GPIOPORT=(0 PM.04 PM.03 PM.05 PM.06 PQ.01 PEE.06 PEE.05)
GPIODIR=(0 in in out out in in in)

num=

function gpio()
{
	if [[ $# -lt 1 ]]; then
		echo -e "${FUNCNAME}: Parameter Error."
		exit 1
	fi

	local SYSFS_GPIO_PORT=${SYSFS_GPIO}/${GPIOPORT[${num}]}
	# GPIO Init
	if [[ ! -d ${SYSFS_GPIO_PORT} ]]; then
		echo ${GPIONUM[${num}]} > ${SYSFS_GPIO}/export
		echo ${GPIODIR[${num}]} > ${SYSFS_GPIO_PORT}/direction
		echo 0  > ${SYSFS_GPIO_PORT}/active_low
	fi

	# GPIO SET
	if [[ $# -ge 2 ]]; then
		local GPIO_VALUE=$2
		echo ${GPIO_VALUE} > ${SYSFS_GPIO_PORT}/value
	fi

	# Show Current GPIO Value
	echo "GPIO ${GPIONUM[${num}]}, ${GPIOPORT[${num}]}"
	echo "Direction : $(cat ${SYSFS_GPIO_PORT}/direction)"
	echo "Active Low: $(cat ${SYSFS_GPIO_PORT}/active_low)"
	echo "Value     : $(cat ${SYSFS_GPIO_PORT}/value)"
}

function usage()
{
	echo -e "\nUsage: $0 <num> [value]"
	echo -e "  <num> can be 1 ~ 7"
	echo -e "   num=1 ---- P11 DI_1"
	echo -e "   num=2 ---- P11 DI_2"
	echo -e "   num=3 ---- P11 DO_1"
	echo -e "   num=4 ---- P11 DO_2"
	echo -e "   num=5 ---- P4E e21 (reserved)"
	echo -e "   num=6 ---- P4E e22 (reserved)"
	echo -e "   num=7 ---- P4E e23 (reserved)"
	echo -e ""
}

if [[ $(id -u) -ne 0 ]]; then
    echo -e "\nERROR: please run as root\n"
    exit 1
fi

if [[ $# -lt 1 ]]; then
	usage
	exit 1
fi

if [[ $1 -lt 1 ]] || [[ $1 -gt 7 ]]; then
	usage
	exit 1
fi

num=($1)
shift

gpio ${GPIONUM[${num}]} $@
